package google.sites.model.commands.webpage;

import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.sites.BaseContentEntry;
import com.google.gdata.data.sites.SitesLink;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.CommandException;
import google.sites.model.ContentEntryFactory;
import google.sites.model.Kind;
import google.sites.model.Model;
import google.sites.model.commands.SitesCommand;

import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 02-10-2013
 * Time: 18:15
 */
public class CreateWebPage extends SitesCommand {
    private String title;
    private String parentId;

    @Override
    protected void protectedExecute() throws CommandException {
        try {
            BaseContentEntry<?> entry = ContentEntryFactory.create(Kind.webpage);

            entry.setTitle(new PlainTextConstruct(title));
            setContentBlob(entry);

            if (parentId != null) {
                if (parentId.lastIndexOf("/") == -1)
                    parentId = getContentFeedUrl() + parentId;

                entry.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentId);
            }

            setResult(getService().insert(new URL(getContentFeedUrl()), entry));
        } catch (Model.Exception | IOException | ServiceException e) {
            throw new CommandException(e);
        }
    }

    public CreateWebPage setTitle(String title) {
        this.title = title;
        return this;
    }

    public CreateWebPage setParentId(String parent) {
        this.parentId = parent;
        return this;
    }
}
